package com.mfn.sportjava.config;

import io.milvus.client.MilvusServiceClient;
import io.milvus.param.ConnectParam;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author Anyang
 * @version 1.0.0
 * @date 2025/04/15 09:04:29
 * @description
 */
@Configuration
public class KnowledgeBaseConfig {

    private static final Logger log = LoggerFactory.getLogger(KnowledgeBaseConfig.class);

    @Value("${spring.milvus.host}")
    private String milvusHost;

    @Value("${spring.milvus.port:19530}")
    private int milvusPort;

    @Value("${spring.milvus.database-name:default}")
    private String databaseName;

    // 其他Milvus连接参数（用户名、密码、TLS）
    // @Value("${spring.milvus.username:#{null}}")
    // private String username;
    // @Value("${spring.milvus.password:#{null}}")
    // private String password;


    @Bean(destroyMethod = "close")
    public MilvusServiceClient milvusServiceClient() {
        log.info("正在连接到Milvus，地址为 {}:{}，数据库名为 '{}'", milvusHost, milvusPort, databaseName);
        ConnectParam.Builder connectBuilder = ConnectParam.newBuilder()
                .withHost(milvusHost)
                .withPort(milvusPort)
                .withDatabaseName(databaseName);

        // 配置了认证信息，则添加认证
        // if (username != null && !username.isEmpty() && password != null) {
        //     log.info("为Milvus用户 {} 使用认证", username);
        //     connectBuilder.withAuthorization(username, password);
        // }

        try {
            MilvusServiceClient client = new MilvusServiceClient(connectBuilder.build());
            log.info("成功连接到Milvus。");
            return client;
        } catch (Exception e) {
            log.error("连接Milvus失败：{}", e.getMessage(), e);
            // 抛出异常以防止应用程序在没有Milvus的情况下启动。
            throw new RuntimeException("无法初始化Milvus客户端", e);
        }
    }
}